﻿namespace Pps.Gui
{
    using Pps.Gui.Base;

    public delegate void TouchEventHandler();
    public delegate void ClickEventHandler();
    public delegate void LostFocusEventHandler();

    public abstract class Control : DisplayObjectContainer
    {
        public event TouchEventHandler Touched;
        public event ClickEventHandler Clicked;
        public event LostFocusEventHandler LostFocus;

        private Window parent;

        public Control()
            : this(50, 40)
        {
        }

        public Control(int width, int height)
            : this(0, 0, width, height)
        {
        }

        public Control(int x, int y, int width, int height)
            : base(x, y, width, height)
        {
            this.parent = null;
        }

        public void AddChildControl(Control child)
        {
            this.AddChild(child);
        }

        public void RemoveChildControl(Control child)
        {
            this.RemoveChild(child);
        }

        public Window Parent
        {
            get { return this.parent; }
            internal set { this.parent = value; }
        }

        public override void Invalidate()
        {
            if (this.parent != null && this.parent.IsActive() == true)
            {
                this.Render();
                Graphics.Flush(parent.X + this.X, parent.Y + this.Y, this.Width, this.Height);
            }
        }

        internal override void Render()
        {
            Graphics gfx = new Graphics(parent.X, parent.Y);

            for (int i = 0; i < this.Children.Count; i++)
            {
                Control c = this.Children[i] as Control;

                if (c != null)
                {
                    if (c.Visible == true)
                    {
                        c.Render();
                    }
                    else
                    {
                        gfx.DrawRectangle(this.BackgroundColor, 0, this.X, this.Y, this.Width, this.Height, 0, 0, this.BackgroundColor, 0, 0, this.BackgroundColor, 0, 0, 256);
                    }
                }
            }

            this.Paint(gfx);
        }

        internal void OnLostFocusEvent()
        {
            if (this.LostFocus != null)
            {
                this.LostFocus();
            }
        }

        internal void OnTouchedEvent()
        {
            if (this.Touched != null)
            {
                this.Touched();
            }
        }

        internal void OnClickedEvent()
        {
            if (this.Clicked != null)
            {
                this.Clicked();
            }
        }
    }
}